//
//  PhoneViewModel.swift
//  ShouChong
//
//  Created by yw on 2024/8/19.
//

import Foundation
import WatchConnectivity

class PhoneViewModel:NSObject,ObservableObject {
    private let session:WCSession
    
    init(session: WCSession = .default) {
        self.session = session
        super.init()
        self.session.delegate = self
        self.session.activate()
    }
}


extension PhoneViewModel:WCSessionDelegate {
    func sessionDidBecomeInactive(_ session: WCSession) {
        
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
        
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {
        
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        print("收到watch端的信息：\(message)")
        replyHandler(["msg":"success"])
        if let msg = message as? [String:String] {
            let sendData = [
                "count":msg["count"],
//                "calorie":"0",
                "remark":msg["remark"],
                "other":"ios",
                "duration":msg["time"],
                "isWatch":msg["isWatch"],
                "heartRate":msg["heartRate"]
            ]
            DPrint("上传用户使用记录\(sendData)")
            YWNetworkTool.share().requestJson(url: "info/setNNUserHistory", parameters: sendData) { res in
                
                DPrint(res)
            } responseFailBlock: { error, code in
                
                DPrint(error)
                YWToast.show(text: "watch端记录上传失败",duration: 0.8)
            }
        }
        
    }
    
}
